<template> 
	<a-spin   :indicator="indicator"  tip="正在加载中..."  :spinning='spinning'  :delay="delayTime">
		<a-form :layout="formLayout"  :form="form"  @submit="handleSubmit"> 

			<a-form-item  :label-col="formItemLayout.labelCol"  :wrapper-col="formItemLayout.wrapperCol"
				label="项目名称"  
				>
				<a-input placeholder="请输入项目名称"  v-decorator="['name', baseform.name]" /> 
			</a-form-item>  
			<a-form-item   :label-col="formItemLayout.labelCol"  :wrapper-col="formItemLayout.wrapperCol"
				label="项目负责人" 
				>
				<a-select  placeholder="请选择"  v-decorator="['principalCode',baseform.principalCode]"  >
					<a-select-option v-for="(item,index) in dutyPersonOptions" :key="index" :value="item.code" >
						{{item.name}}
					</a-select-option>
				</a-select>
			</a-form-item> 
			<a-form-item  :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol"  
				label="买家公司" 
			>	
				<a-input style='display: none;' v-decorator="['buyerCode', baseform.buyerCode]" />  
				<loadSelect  ref='selectop_buyer'  :selected="selectedBuy"  url='/op/ent/get_ent_list?supOrBuyer=2' :isEdit='isEdit' v-on:valueChange='(val)=>buyerValueChange(val) '  v-on:request_list_finished='request_list_finished(1)' v-on:errorTip='errorTip(1)'></loadSelect>
			</a-form-item>
			<a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol"
				label="供应商公司" 
			>
				<a-input style='display: none;' v-decorator="['supplierCode', baseform.supplierCode]" /> 
				<loadSelect  ref='selectop_supply'  :selected="selectedSupply"  url='/op/ent/get_ent_list?supOrBuyer=1' :isEdit='isEdit' v-on:valueChange='(val)=>supplyValueChange(val) '  v-on:request_list_finished='request_list_finished(2)' v-on:errorTip='errorTip(2)'></loadSelect> 
			</a-form-item> 
			<a-form-item  :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol"
				label="项目相关人员" 
			>
				<a-select  mode="multiple" placeholder="请选择" v-decorator="['projectPersonnel',baseform.projectPersonnel]"> 
					<a-select-option v-for="(item,index) in dutyPersonOptions" :key="index" :value="item.code" >
						{{item.name}}
					</a-select-option>
				</a-select>
			</a-form-item>
			<a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol"
				label="项目状态" 
			>
				<a-select  style="width: 120px"  v-decorator="['prjStatus',baseform.prjStatus]" >
				      <a-select-option value="1">未签约</a-select-option>
				      <a-select-option value="3">签约中</a-select-option>
				      <a-select-option value="2" >已签约</a-select-option>
			    </a-select>
			</a-form-item>
			<a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol"
				label="相关资料" 
			> 
				<fileUpload   :fileList='fileData'  v-on:uploading='($event)=>{fileData = $event.fileList}'  v-on:removeFile='removeFile($event,1)'    ></fileUpload>
			</a-form-item>
			<a-form-item  style='display: none;'>
				<a-input  v-decorator='["code",baseform.code]'  />
			</a-form-item>
			<a-form-item :wrapper-col="buttonItemLayout.wrapperCol" >
				<a-button type="primary"  html-type="submit"  class='mr20'>
					提交
				</a-button> 
				<a-button @click='back_common()'> 取消 </a-button> 
			</a-form-item>
	</a-form>
	</a-spin> 
</template>

<script> 
import  loadSelect  from  '@/components/common/loadSelect'
import  fileUpload  from  '@/components/common/fileUpload'

import { customerList }  from  '@/api/customer/index'
import { listUser_of_inner }  from  '@/api/system/index' 
import { submitProject,detailProject }  from  '@/api/project/index'

export default {
  name: 'projectAdd',
  data () { 
    this.timeout = null;
	this.currentValue = '';
    return {
    	spinning:false,
    	indicator:<a-icon type="loading-3-quarters"  spin  style="{ fontSize: '16px' }"/> ,
    	delayTime:1000,

    	dutyPersonOptions:[],//option_负责人
    	/*form  布局*/
      	formLayout:'horizontal',
      	/*form-rule*/
	    baseform:{
      		name: {rules: [{ required: true, message: '请输入项目名称' },{ whitespace : true ,message:'当前输入不能为空'}]},
      		principalCode: {rules: [{ required: true, message: '请输入项目名称' },{ whitespace : true ,message:'当前输入不能为空'}]},
      		prjStatus: {rules: [{ required: true, message: '请选择' }]},
      		// supplierCode: {rules: [{ required: true, message: '请输入项目名称' },{ whitespace : true ,message:'当前输入不能为空'}]},
      		code:{initialValue:''},
      		buyerCode: {initialValue:''},
      		supplierCode: {initialValue:''},
      		projectPersonnel:{initialValue:[]}
      		
      	},
      	/*form v-model */    
      	fileData:[],  

		isEdit:false,
		currentCode:'',//prjcode 
		//loadSelected_option_list_selectedValue
		selectedBuy:'',
		selectedSupply:'', 
   		//loadSelected_option_editFinished
		firstFlag:false,
		secFlag:false,
                                                                
    }
  },
  beforeCreate () {
    this.form = this.$form.createForm(this);
    
  },
  created(){ 
  		if(this.$route.query.code){
  			this.isEdit = true
  			this.currentCode = this.$route.query.code 
  			this.baseform.code.initialValue = this.currentCode
  		}
  		//先判断当前状态，使isEdit完全正确
  		this.pageInit()
  },
  mounted(){
  	 
  },
  methods:{
  	//初始化userlist
  	pageInit(){ 
  		let userFun = new Promise(function(resolve,reject){
  			listUser_of_inner({pageSize:100}).then((res)=>{ 
	  			 if(res.data.flag == true){
	  			 	resolve(res.data.dataList)
	  			 }
	  			 else{
	  			 	reject()
	  			 }
	  		})
  		})
  		if(this.isEdit == false){
  			userFun.then((result)=> { 
			   this.dutyPersonOptions = result 
			}).catch((reason)=> {
			    // console.log('失败：' + reason);
			});
  		}
  		/*当一个接口需要依赖很多个接口的请求数据  或者  一个依赖另一个，另一个再依赖另一个。先调用getData1，再调用getData2，再调用getData3  ...
			*业务场景：
			*需先请求userlist-option
			*再请求detail
			*再根据买方和供应方的code请求option ，再设置form field
  		*/ 
  		/** 在编辑情况下才去请求这个promise*/ 
  		else if(this.isEdit == true){ 
  			
  			let detailFun = new Promise((resolve,reject)=>{
	  			detailProject(this.currentCode).then((res)=>{
	  				if(res.data.flag == true){
	  					resolve(res.data.data)
	  				}
	  				else{
	  					reject()
	  				}
	  			})
  			})
  			this.spinning = true 
			//Promise的all方法，等数组中的所有promise对象都完成执行
			Promise.all([userFun,detailFun]).then(([res1,res2])=>{ 
				this.dutyPersonOptions = res1   

				let data = res2
  				this.form.setFieldsValue({ 
	    			code:data.code,
      				name: data.name,
		      		principalCode:data.principalCode,
		      		buyerCode:data.buyerCode,
		      		supplierCode:data.supplierCode, 
		      		prjStatus:data.prjStatus, 
			      })
  				//项目相关人员 -多选回填 
  				this.form.setFieldsValue({projectPersonnel:this.Recontent_fromcode(data.projectPersonnel)})
  				/*过滤已上传文件 ，并为后续上传，存储保持一致设定字段*/
  				this.fileData = this.FormEditFile(data.projectFiles)
 
  				this.selectedBuy = data.buyerCode 
				this.selectedSupply = data.supplierCode 
				this.$refs.selectop_buyer.$emit('edit')
				this.$refs.selectop_supply.$emit('edit') 

			})
  		}
  	}, 

  	/*提交表单*/
	handleSubmit (e) {
		let that = this,url 
		e.preventDefault(); 
		this.form.validateFields((err, values) => {
			if (!err) {
			  console.log('Received values of form: ', values);
			  values.projectPersonnel = this.RequireCodeToSub(values.projectPersonnel)  
			  values.projectFiles = this.ReFileCodeToSub(this.fileData)
			  //没有填写提示
			  if(values.buyerCode == '' || values.supplierCode == ''){
			  	this.$error({
		          title: '错误提示',
		          content: '请选择买家公司或供应商公司',
		          okText:'我知道了'
		        });
		        return
			  }
			   
			  if(that.isEdit == true){
			  	url = '/op/project/modify_project'    //修改 项目
			  }
			  else{
			  	url='/op/project/create_project'      //新增 项目
			  }

			  submitProject(url,values).then((res)=>{
			  	if(res.data.flag == true){
			  		that.$message.success(res.data.msg)
			  		that.$router.push('/project')
			  	}
			  })
			}
			else{
				console.log(err)
			}
		});
	},
		 
	   
	/*组件函数*/
	//选定option值
    buyerValueChange(val){ 
    	  this.form.setFieldsValue({buyerCode:val})
    	  this.selectedBuy = val
    }, 
    /*供应商公司  input-change*/ 
    supplyValueChange(val){ 
    	this.form.setFieldsValue({supplierCode:val})
    	this.selectedSupply = val
    },
    request_list_finished(num){ 
    	if(num==1){
    		this.firstFlag =true
    	}
    	if(num==2){
    		this.secFlag =true
    	}
    	//编辑状态下list请求完毕 
    	this.spinning = !(this.firstFlag && this.secFlag)  
    },
    errorTip(num){
    	if(num==1){
    		this.$error({
	          title: '错误提示',
	          content: '您所填写的买家公司已被删除，请联系管理员或重新建项。',
	          okText:'我知道了'
	        });
	        this.selectedBuy = ''
	        this.form.setFieldsValue({ buyerCode:'' })
    	}
    	 if(num==2){
    		this.$error({
	          title: '错误提示',
	          content: '您所填写的供应商公司已被删除，请联系管理员或重新建项。',
	          okText:'我知道了'
	        });
	        this.selectedSupply = ''
	        this.form.setFieldsValue({ supplierCode:'' })
    	}
    	this.spinning = false
    },
 
    /*移除文件*/
    removeFile(e){
      this.removeFile_fromList(e,this.fileData) 
    },
  },
	computed: {
		formItemLayout () {
			const { formLayout } = this;
			return formLayout === 'horizontal' ? {
			labelCol: {md:{span:5},lg:{ span: 7 }},  //label 标签布局
			wrapperCol: {xxl:{ span: 8 },xl:{ span : 11},lg:{ span :14 },md:{ span : 16 },xs:{ span :24}}, //需要为输入控件设置布局样式时，使用该属性，用法同 labelCol
			} : {};
		},
		buttonItemLayout () {
			const { formLayout } = this;
			return formLayout === 'horizontal' ? {
			wrapperCol: { span: 14, offset: 7 },
			} : {};
		},
		 
	},
  components: {
    loadSelect,
    fileUpload
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
/*.ant-input{width: 200px;}*/
</style>
